import { useEffect } from "react"
import { useDispatch, useSelector } from "react-redux"
import { RootState, RootThunkAction } from "@/types/store";

export function useInitialState<T extends keyof RootState>(
  action: () => RootThunkAction,
  stateName: T
) {
  const dispatch = useDispatch();

  // 进入组件，就需要发送请求
  useEffect(() => {
    dispatch(action())
  }, [dispatch, action])

  // 进入组件，需要获取redux的数据
  const state = useSelector((state: RootState) => state[stateName]);

  return state;
}